<template>
  <el-container>
    <el-dialog title="编辑收费路段" :visible.sync="visible" :before-close="handleClose" center>
      <el-form ref="formParam" :model="formParam"
               label-position="left" label-width="100px" :rules="rules"  style="width: 400px; margin-left:50px;">
        <el-form-item label="所属停车场" prop="park_name">
          <el-input readonly  v-model="formParam.park_name"></el-input>
        </el-form-item>
        <el-form-item label="路段编号" prop="chargeRoad_no">
          <el-input readonly v-model="formParam.chargeRoad_no" ></el-input>
        </el-form-item>
        <el-form-item label="路段名称" prop="chargeRoad_name">
          <el-input v-model="formParam.chargeRoad_name" clearable placeholder="路段名称"></el-input>
        </el-form-item>
        <el-form-item label="收费单位" prop="chargeUnit_name">
          <el-input v-model="formParam.chargeUnit_name" @click.native="openDwDialog"
                    placeholder="收费单位"></el-input>
        </el-form-item>
        <el-form-item label="路段状态" prop="roadStatus">
          <el-select v-model="formParam.roadStatus" placeholder="路段状态">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div  slot="footer" class="dialog-footer">
        <el-button @click="selectPlaceByPark" class="btn-search_four" type="success">选择泊位
        </el-button>
        <el-button @click="updateChargesUnit('formParam')" class="btn-search" type="primary">保存
        </el-button>
        <el-button class="btn-search" @click="resetForm('formParam')" >取消
        </el-button>
      </div>
    </el-dialog>

    <!--泊位信息弹框-->
    <el-dialog title="泊位信息" :visible.sync="berthVisible" center
               :before-close="handleBerthClose">
      <el-table :data="berth.berthList" ref="multipleTable" v-loading="berth.berthLoading"
                @select="berthClickRows"
                @select-all="selectAll"
                :row-key="getRowKeys"
                element-loading-text="给我一点时间" border fit highlight-current-row stripe>
        <el-table-column :reserve-selection="true" fixed type="selection" align="center"></el-table-column>
        <el-table-column align="center" label="所在停车场" width="180">
          <template slot-scope="scope">
            <span>{{scope.row.place_parkname}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="泊位编号" width="100">
          <template slot-scope="scope">
            <span>{{scope.row.place_id}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="所在路段" width="180">
          <template slot-scope="scope">
            <span>{{scope.row.place_chargeunitname}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="路段内编号" width="150">
          <template slot-scope="scope">
            <span>{{scope.row.place_no}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="收费单位" width="200">
          <template slot-scope="scope">
            <span>{{scope.row.place_sfdwname}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="泊位类型" width="100">
          <template slot-scope="scope">
            <span>{{scope.row.place_type === '1' ? '真实泊位':'虚拟泊位'}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="泊位状态" width="100">
          <template slot-scope="scope">
            <span>{{scope.row.place_status === '1' ? '启用':'未启用'}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="在停车辆">
          <template slot-scope="scope">
            <span>{{scope.row.place_car}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="泊位尺寸">
          <template slot-scope="scope">
            <span>{{scope.row.place_size}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="备注">
          <template slot-scope="scope">
            <span>{{scope.row.place_remark}}</span>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-berth" style="text-align: right">
        <el-pagination background small :total="berth.total" :page-sizes="[10,20,30,50]"
                       :page-size="berthQuery.limit"
                       :current-page="berthQuery.page"
                       @size-change="berthHandlerSizeChange"
                       @current-change="berthHandlerCurrentChange"
                       layout="total, sizes, prev, pager, next, jumper">
        </el-pagination>
      </div>
      <div class="pagination-berth" align="center">
        <el-button @click="berthVisible = false" class="btn-search" type="primary">确定
        </el-button>
        <el-button @click="clearSelectBerth" class="btn-search">取消
        </el-button>
      </div>
    </el-dialog>

    <person-child-dialog-dw :dialogDwVisible.sync="dwVisible"
                            @dwName5="selectDwname"
                            :dwType="dwType"
                            :dwLoading.sync="dwLoading">
    </person-child-dialog-dw>
  </el-container>
</template>

<script>
  import ParkingDialog from '../../operatingManagement/parkingflowChild/parkingDialog'
  import { selectBerthByParkno, updateChargesUnit } from '../../../api/parkingResource/tollSelection'
  import PersonChildDialogDw from '../../organizationManagement/personChild/personChildDialogDw'

  export default {
    components: {
      PersonChildDialogDw,
      ParkingDialog
    },
    name: 'charge-unit-edit',
    data() {
      return {
        visible: false,
        berthVisible: false,
        rowArray: {},
        dwVisible: false,
        dwType: 4,
        dwLoading: true,
        hasBerths: [],
        selectRows: 0,
        formParam: {
          park_name: '',
          park_no: '',
          chargeRoad_no: '',
          chargeRoad_name: '',
          roadStatus: '1',
          chargeUnit_no: '',
          chargeUnit_name: '',
          unit_places: ''
        },
        // 获取row的key值
        getRowKeys(row) {
          return row.place_id
        },
        selectedData: [],
        berth: {
          total: 0,
          berthLoading: true,
          berthList: []
        },
        berthQuery: {
          page: 1,
          limit: 10
        },
        options: [{
          value: '1',
          label: '启用'
        }, {
          value: '2',
          label: '未启用'
        }],
        rules: {
          chargeRoad_name: [
            { required: true, message: '请输入收费路段名称', trigger: 'blur' }
          ],
          chargeRoad_no: [
            { required: true, message: '请输入收费路段编号', trigger: 'blur' }
          ],
          park_name: [
            { required: true, message: '请选择停车场', trigger: 'change' }
          ]
        }
      }
    },
    watch: {
      editChargeVisible(val) {
        this.visible = val
        this.formParam.park_name = this.rowArray.unit_parkname
        this.formParam.park_no = this.rowArray.unit_park
        this.formParam.chargeUnit_no = this.rowArray.unit_sfdw
        this.formParam.chargeUnit_name = this.rowArray.unit_sfdwname
        this.formParam.roadStatus = this.rowArray.unit_status
        this.formParam.chargeRoad_name = this.rowArray.unit_name
        this.formParam.chargeRoad_no = this.rowArray.unit_no
        selectBerthByParkno({ page: 1, limit: 10000 }, this.formParam.park_no).then(
          res => {
            this.hasBerths = []
            for (const i in res.list) {
              if (res.list[i].place_chargeunit === this.formParam.chargeRoad_no) {
                this.hasBerths.push(res.list[i].place_id)
              }
            }
            console.log(this.hasBerths)
          }
        )
      },
      editRow(val) {
        this.rowArray = val
        // if (val.length === 1) {
        //   this.rowArray = val[0]
        // }
      },
      visible(val) {
        this.$emit('update:editChargeVisible', val)
      }
    },
    props: [
      'editChargeVisible', 'editRow'
    ],

    methods: {
      /* 关闭弹框之前操作*/
      handleClose(done) {
        this.visible = false
      },
      handleBerthClose(done) {
        this.berthVisible = false
        this.berthQuery.page = 1
        this.berthQuery.limit = 10
      },
      /* 根据停车场查询泊位信息*/
      selectPlaceByPark() {
        if (this.formParam.park_name === '' || this.formParam.park_no === '') {
          this.addError()
          return
        }
        this.berthVisible = true
        selectBerthByParkno(this.berthQuery, this.formParam.park_no).then(
          res => {
            this.berth.berthList = res.list
            this.berth.total = res.count
            this.berth.berthLoading = false
            if (this.berth.berthList) {
              this.$refs.multipleTable.clearSelection()
              this.berth.berthList.forEach(row => {
                for (const i in this.hasBerths) {
                  if (row.place_id === this.hasBerths[i]) {
                    this.$refs.multipleTable.toggleRowSelection(row, true)
                  }
                }
              })
            }
          }
        )
      },
      openDwDialog() {
        this.dwVisible = true
      },
      selectDwname(val) {
        this.formParam.chargeUnit_no = val.orgno
        this.formParam.chargeUnit_name = val.orgname
      },

      /* 点击泊位编号时操作*/
      berthClickRows(rows, row) {
        let flag = 0 // 移除
        for (const i in rows) {
          if (row.place_id === rows[i].place_id) {
            flag = 1 // 添加操作
            break
          }
        }
        if (flag === 0) {
          for (const j in this.hasBerths) {
            if (this.hasBerths[j] === row.place_id) {
              this.hasBerths.splice(j, 1)
            }
          }
        } else {
          if (row.place_chargeunit !== null && row.place_chargeunit !== '' && row.place_chargeunit !== this.formParam.chargeRoad_no) {
            this.$confirm('此泊位已被其他收费路段占用, 是否继续?', '提示', {
              confirmButtonText: '继续',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.$refs.multipleTable.toggleRowSelection(row, true)
              this.hasBerths.push(row.place_id)
            }).catch(() => {
              this.$refs.multipleTable.toggleRowSelection(row, false)
            })
          } else {
            this.hasBerths.push(row.place_id)
          }
        }
        this.selectRows = rows.length
      },
      selectAll(rows) {
        var v = this
        // remove
        console.log('前一次数量：' + this.selectRows)
        console.log('数量：' + rows.length)
        if (rows.length <= this.selectRows) {
          for (const i in v.berth.berthList) {
            for (const j in v.hasBerths) {
              if (v.hasBerths[j] === v.berth.berthList[i].place_id) {
                v.hasBerths.splice(j, 1)
                break
              }
            }
          }
        } else {
          for (const i in v.berth.berthList) {
            let flag = false
            for (const j in v.hasBerths) {
              if (v.hasBerths[j] === v.berth.berthList[i].place_id) {
                flag = true
                break
              }
            }
            if (!flag) {
              if (v.berth.berthList[i].place_chargeunit !== null && v.berth.berthList[i].place_chargeunit !== '' && v.berth.berthList[i].place_chargeunit !== this.formParam.chargeRoad_no) {
                this.$message.warning('某些泊位被其他收费路段占用，请检查确认')
                v.hasBerths.push(v.berth.berthList[i].place_id)
              } else {
                v.hasBerths.push(v.berth.berthList[i].place_id)
              }
            }
          }
        }
        this.selectRows = rows.length
        console.log(v.hasBerths)
      },
      /* 添加收费路段按钮*/
      updateChargesUnit(formParam) {
        this.$refs[formParam].validate((valid) => {
          if (valid) {
            if (this.hasBerths.length !== 0) {
              this.hasBerths.forEach((value, index) => {
                if (index !== 0) {
                  this.formParam.unit_places += ','
                }
                this.formParam.unit_places += value
              })
            }
            updateChargesUnit(this.formParam).then(
              () => {
                this.addSuccess()
                this.visible = false
                this.formParam.unit_places = ''
                this.$emit('addAfterQueryChargeUnit')
              },
              (error) => {
                console.log(error)
              }
            )
          } else {
            return false
          }
        })
      },
      /* 关闭泊位选择按钮*/
      clearSelectBerth() {
        this.selectedData = []
        this.$refs.multipleTable.clearSelection()
        this.berthVisible = false
      },
      /* 泊位分页操作*/
      berthHandlerCurrentChange(num) {
        this.berthQuery.page = num
        this.selectPlaceByPark()
      },
      berthHandlerSizeChange(num) {
        this.berthQuery.limit = num
        this.selectPlaceByPark()
      },
      resetForm(formParam) {
        this.$refs[formParam].resetFields()
        this.visible = false
      },
      /* 提示信息*/
      addError() {
        this.$message.error('停车场设置有误')
      },
      addSuccess() {
        this.$message.success('编辑成功')
      }
    }
  }
</script>

<style scoped>
  .button-margin {
    margin-left: 10px;
  }

  .pagination-berth {
    margin-top: 15px;
  }
</style>

